package com.tvapp;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;

public class PlayerActivity extends AppCompatActivity {
    private static final String TAG = "PlayerActivity";
    private PlayerView playerView;
    private TextView channelNameView;
    private ProgressBar loadingIndicator;
    private SimpleExoPlayer player;
    private Channel currentChannel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        playerView = findViewById(R.id.player_view);
        channelNameView = findViewById(R.id.channel_name);
        loadingIndicator = findViewById(R.id.loading_indicator);

        // 获取从上一个Activity传递过来的频道信息
        if (getIntent().hasExtra("channel")) {
            currentChannel = (Channel) getIntent().getSerializableExtra("channel");
            channelNameView.setText(currentChannel.getName());
        }
    }

    private void initializePlayer() {
        if (currentChannel == null) {
            Log.e(TAG, "No channel selected");
            return;
        }

        try {
            // 创建自适应的轨道选择器
            AdaptiveTrackSelection.Factory trackSelectionFactory = new AdaptiveTrackSelection.Factory();
            DefaultTrackSelector trackSelector = new DefaultTrackSelector(this, trackSelectionFactory);
            
            // 创建ExoPlayer实例
            player = new SimpleExoPlayer.Builder(this)
                    .setTrackSelector(trackSelector)
                    .build();
            
            // 设置播放器视图
            playerView.setPlayer(player);
            
            // 创建数据源工厂
            DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this,
                    Util.getUserAgent(this, getString(R.string.app_name)));
            
            // 从频道URL创建媒体源
            Uri videoUri = Uri.parse(currentChannel.getUrl());
            MediaItem mediaItem = MediaItem.fromUri(videoUri);
            
            // 设置播放状态监听
            player.addListener(new Player.Listener() {
                @Override
                public void onIsLoadingChanged(boolean isLoading) {
                    loadingIndicator.setVisibility(isLoading ? View.VISIBLE : View.GONE);
                }

                @Override
                public void onPlaybackStateChanged(int playbackState) {
                    switch (playbackState) {
                        case Player.STATE_BUFFERING:
                            loadingIndicator.setVisibility(View.VISIBLE);
                            break;
                        case Player.STATE_READY:
                            loadingIndicator.setVisibility(View.GONE);
                            break;
                        case Player.STATE_ENDED:
                            // 播放结束，可以进行相关处理
                            break;
                        case Player.STATE_IDLE:
                            loadingIndicator.setVisibility(View.GONE);
                            break;
                    }
                }

                @Override
                public void onPlayerError(com.google.android.exoplayer2.ExoPlaybackException error) {
                    Log.e(TAG, "Playback error: " + error.getMessage());
                    loadingIndicator.setVisibility(View.GONE);
                }
            });
            
            // 准备并开始播放
            player.setMediaItem(mediaItem);
            player.prepare();
            player.setPlayWhenReady(true);
            
        } catch (Exception e) {
            Log.e(TAG, "Error initializing player: " + e.getMessage());
            loadingIndicator.setVisibility(View.GONE);
        }
    }

    private void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (Util.SDK_INT >= 24) {
            initializePlayer();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if ((Util.SDK_INT < 24 || player == null)) {
            initializePlayer();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (Util.SDK_INT < 24) {
            releasePlayer();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (Util.SDK_INT >= 24) {
            releasePlayer();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 处理遥控器按键事件
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                finish();
                return true;
            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
                if (player != null) {
                    if (player.isPlaying()) {
                        player.pause();
                    } else {
                        player.play();
                    }
                }
                return true;
            default:
                return super.onKeyDown(keyCode, event);
        }
    }
}